<?php

namespace App\Home\Controllers\Auth;

use App\Home\Controllers\Controller;
use App\Home\Models\Config;
use App\Home\Models\User;
use App\Home\Utils\Home;
use App\Home\Resources\UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function login(Request $request, User $user)
    {
        $rules = [
            'phone' => 'required|string',
            'password' => 'required|string',
        ];
        $inputs = $request->validate($rules);
        $inputs['password'] = md5(md5($inputs['password']));
        $user = User::findUser($inputs);
        if ($user) {
            // 更新最后登录时间，并且存入token
            $user->update([
                'last_login_at' => date('Y-m-d H:i:s'),
                'api_token' => User::makeToken(),
            ]);
            session()->put('user',$user);
            return $this->created(UserResource::make($user));
        } else {
            return $this->error('用户名或密码错误');
        }
    }

    public function logout(Request $request, User $user)
    {
        // 更新api_token为空
        $user->where(['id'=>$request->user['id']])->update([
            'api_token' => null,
        ]);
        session()->put('user',null);
        return $this->noContent();
    }
}
